// +----------------------------------------------------------------------
// | ShopSuite商城系统 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 随商信息技术（上海）有限公司
// +----------------------------------------------------------------------
// | 未获商业授权前，不得将本软件用于商业用途。禁止整体或任何部分基础上以发展任何派生版本、
// | 修改版本或第三方版本用于重新分发。
// +----------------------------------------------------------------------
// | 官方网站: https://www.shopsuite.cn  https://www.modulithshop.cn
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本公司对该软件产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细见https://www.modulithshop.cn/policy
// +----------------------------------------------------------------------
package com.suisung.shopsuite.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suisung.shopsuite.account.model.entity.UserBase;
import com.suisung.shopsuite.account.model.entity.UserDistribution;
import com.suisung.shopsuite.account.model.entity.UserInfo;
import com.suisung.shopsuite.account.model.req.UserDistributionListReq;
import com.suisung.shopsuite.account.model.vo.UserDistributionVo;
import com.suisung.shopsuite.account.repository.UserBaseRepository;
import com.suisung.shopsuite.account.repository.UserDistributionRepository;
import com.suisung.shopsuite.account.repository.UserInfoRepository;
import com.suisung.shopsuite.account.service.UserDistributionService;
import com.suisung.shopsuite.common.api.ResultCode;
import com.suisung.shopsuite.common.exception.BusinessException;
import com.suisung.shopsuite.common.utils.CheckUtil;
import com.suisung.shopsuite.common.utils.CommonUtil;
import com.suisung.shopsuite.core.web.service.impl.BaseServiceImpl;
import com.suisung.shopsuite.pay.model.entity.DistributionCommission;
import com.suisung.shopsuite.pay.repository.DistributionCommissionRepository;
import com.suisung.shopsuite.sys.service.ConfigBaseService;
import com.suisung.shopsuite.trade.model.entity.DistributionGeneratedCommission;
import com.suisung.shopsuite.trade.repository.DistributionGeneratedCommissionRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.suisung.shopsuite.common.utils.I18nUtil.__;

/**
 * <p>
 * 粉丝来源关系表 服务实现类
 * </p>
 *
 * @author Xinze
 * @since 2021-08-24
 */
@Service
public class UserDistributionServiceImpl extends BaseServiceImpl<UserDistributionRepository, UserDistribution, UserDistributionListReq> implements UserDistributionService {

    @Autowired
    private UserBaseRepository userBaseRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private DistributionCommissionRepository distributionCommissionRepository;

    @Autowired
    private DistributionGeneratedCommissionRepository distributionGeneratedCommissionRepositor;
    @Autowired
    private ConfigBaseService configBaseService;

    @Override
    public Page<UserDistributionVo> getList(UserDistributionListReq userDistributionListReq) {
        Page<UserDistributionVo> output = new Page<>();
        Page<UserDistribution> lists = lists(userDistributionListReq);

        if (lists != null && CollectionUtil.isNotEmpty(lists.getRecords())) {
            BeanUtils.copyProperties(lists, output);
            List<UserDistributionVo> records = BeanUtil.copyToList(lists.getRecords(), UserDistributionVo.class);
            output.setRecords(records);

            List<Integer> userIds = CommonUtil.column(output.getRecords(), UserDistributionVo::getUserId);


            if (CollUtil.isNotEmpty(userIds)) {
                //增加用户昵称
                List<UserInfo> userInfos = userInfoRepository.gets(userIds);
                Map<Integer, String> nickNameMap = new HashMap<>();

                if (CollectionUtil.isNotEmpty(userInfos)) {
                    nickNameMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getUserId, UserInfo::getUserNickname, (k1, k2) -> k1));
                }

                List<DistributionCommission> distributionCommissionList = distributionCommissionRepository.gets(userIds);

                for (UserDistributionVo item : records) {
                    //增加用户昵称
                    if (CollUtil.isNotEmpty(nickNameMap)) {
                        item.setUserNickname(nickNameMap.get(item.getUserId()));
                    }

                    for (DistributionCommission distributionCommission : distributionCommissionList) {
                        if (item.getUserId().equals(distributionCommission.getUserId())) {
                            item.setCommissionAmount(distributionCommission.getCommissionAmount());
                            item.setCommissionBuyAmount0(distributionCommission.getCommissionBuyAmount0());
                            item.setCommissionBuyAmount1(distributionCommission.getCommissionBuyAmount1());
                            item.setCommissionBuyAmount2(distributionCommission.getCommissionBuyAmount2());
                            item.setCommissionSettled(distributionCommission.getCommissionSettled());
                        }
                    }
                }
            }
        }

        return output;
    }

    @Override
    public long getChildNum(Integer userId, Long startTime, Long endTime) {
        QueryWrapper<UserDistribution> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_parent_id", userId);

        if (CheckUtil.isNotEmpty(startTime) || CheckUtil.isNotEmpty(endTime)) {
            queryWrapper.between("user_time", startTime, endTime);
        }

        return count(queryWrapper);
    }

    /**
     * 添加分销用户记录 - 推广员记录
     *
     * @param userParentId
     * @param userActive
     * @return
     */
    public boolean initDistributionUser(Integer userParentId, boolean userActive) {
        if (CheckUtil.isNotEmpty(userParentId)) {
            // 判断用户是否存在
            UserBase userBase = userBaseRepository.get(userParentId);
            if (userBase != null) {
                // 添加父收益表，判断
                DistributionCommission userCommission = distributionCommissionRepository.get(userParentId);
                if (userCommission == null) {
                    DistributionCommission distributionCommission = new DistributionCommission();
                    distributionCommission.setUserId(userParentId);
                    if (!distributionCommissionRepository.saveOrUpdate(distributionCommission)) {
                        throw new BusinessException(ResultCode.FAILED);
                    }
                }

                // 初始化推销员记录
                UserDistribution distributionUser = repository.get(userParentId);
                if (distributionUser == null) {
                    UserDistribution userDistribution = new UserDistribution();
                    userDistribution.setUserId(userParentId);
                    userDistribution.setUserActive(userActive);
                    userDistribution.setUserTime(new Date().getTime());
                    userDistribution.setUserFansNum(1);
                    if (!repository.saveOrUpdate(userDistribution)) {
                        throw new BusinessException(ResultCode.FAILED);
                    }
                } else {
                    distributionUser.setUserFansNum(distributionUser.getUserFansNum() + 1);
                    if (!repository.saveOrUpdate(distributionUser)) {
                        throw new BusinessException(ResultCode.FAILED);
                    }
                }
            }
        }

        return true;

    }

    /**
     * 添加用户关系
     *
     * @param plantformUser
     * @return
     */
    @Override
    public boolean addPlantformUser(UserDistribution plantformUser) {

        if (!repository.saveOrUpdate(plantformUser)) {
            throw new BusinessException(ResultCode.FAILED);
        }

        // 初始化推广员记录
        boolean user_active = configBaseService.getConfig("distribution_user_auto_active", false);
        Integer user_parent_id = plantformUser.getUserParentId();
        initDistributionUser(user_parent_id, user_active);

        // 一级
        DistributionGeneratedCommission user_row = new DistributionGeneratedCommission();

        Integer user_id = plantformUser.getUserId();
        Integer _user_parent_id = plantformUser.getUserParentId();
        Long user_time = plantformUser.getUserTime();

        user_row.setUgcId(String.format("%s-%s-%s", user_id, _user_parent_id, 1));
        user_row.setUserId(user_id);
        user_row.setUserParentId(_user_parent_id);
        user_row.setUgcLevel(1);
        user_row.setUserTime(user_time);
        if (!distributionGeneratedCommissionRepositor.saveOrUpdate(user_row)) {
            throw new BusinessException(ResultCode.FAILED);
        }

        // 二级
        UserDistribution plantform_row = get(_user_parent_id);
        if (plantform_row != null && CheckUtil.isNotEmpty(plantform_row.getUserParentId())) {
            user_row.setUgcId(String.format("%s-%s-%s", user_id, plantform_row.getUserParentId(), 2));
            user_row.setUserId(user_id);
            user_row.setUserParentId(plantform_row.getUserParentId());
            user_row.setUgcLevel(2);
            user_row.setUserTime(user_time);
            if (!distributionGeneratedCommissionRepositor.saveOrUpdate(user_row)) {
                throw new BusinessException(ResultCode.FAILED);
            }

            // 三级
            Integer plant_user_parent_id = plantform_row.getUserParentId();
            plantform_row = get(plant_user_parent_id);

            if (plantform_row != null && CheckUtil.isNotEmpty(plantform_row.getUserParentId())) {
                user_row.setUgcId(String.format("%s-%s-%s", user_id, plantform_row.getUserParentId(), 3));
                user_row.setUserId(user_id);
                user_row.setUserParentId(plantform_row.getUserParentId());
                user_row.setUgcLevel(3);
                user_row.setUserTime(user_time);
                if (!distributionGeneratedCommissionRepositor.saveOrUpdate(user_row)) {
                    throw new BusinessException(ResultCode.FAILED);
                }
            }
        }

        /*
        // 统计数据 检测升级
        AccountUserSns userSns = new AccountUserSns();
        userSns.setUser_id(user_parent_id);
        userSns.setUser_fans(1);

        if (!accountService.saveAndCheckUpdateUserLevel(userSns)) {
            throw new BusinessException(ResultCode.FAILED);
        }

         */
        return true;
    }


    @Override
    public boolean addDistribution(UserDistribution userDistribution) {
        Integer userId = userDistribution.getUserId();
        UserInfo userInfo = userInfoRepository.get(userId);

        if (userInfo == null) {
            throw new BusinessException(__("用户不存在"));
        }
        Integer userIsPa = userDistribution.getUserIsPa();

        if (userIsPa != null && userIsPa > 0) {
            QueryWrapper<UserDistribution> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_is_pa", userIsPa);
            UserDistribution userDist = findOne(queryWrapper);
            //判断该省是否设置代理
            if (userDist != null) {
                throw new BusinessException(__("该省已经设置代理，请勿重复设置！"));
            }
        }
        Integer userIsCa = userDistribution.getUserIsCa();

        if (userIsCa != null && userIsCa > 0) {
            QueryWrapper<UserDistribution> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_is_ca", userIsCa);
            UserDistribution userDist = findOne(queryWrapper);
            //判断该市是否设置代理
            if (userDist != null) {
                throw new BusinessException(__("该市已经设置代理，请勿重复设置！"));
            }
        }

        Integer userIsDa = userDistribution.getUserIsDa();

        if (userIsDa != null && userIsDa > 0) {
            QueryWrapper<UserDistribution> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_is_da", userIsDa);
            UserDistribution userDist = findOne(queryWrapper);
            //判断该区是否设置代理
            if (userDist != null) {
                throw new BusinessException(__("该区已经设置代理，请勿重复设置！"));
            }
        }
        DistributionCommission distributionCommission = distributionCommissionRepository.get(userId);

        if (distributionCommission == null) {
            DistributionCommission commission = new DistributionCommission();
            commission.setUserId(userId);
            distributionCommissionRepository.saveOrUpdate(commission);
        }
        UserDistribution distribution = get(userId);

        if (distribution == null) {
            userDistribution.setUserTime(new Date().getTime());
        }

        return repository.saveOrUpdate(userDistribution);
    }
}
